﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;

using System.Windows.Threading;
using Microsoft.Devices;
using ZXing.QrCode;
using ZXing.Common;
using ZXing;
using Newtonsoft.Json;
using OSChina.Model;

namespace OSChina
{
    public partial class QRPage : PhoneApplicationPage
    {
          private readonly DispatcherTimer _timer;
          private PhotoCameraLuminanceSource _luminance;
          private QRCodeReader _reader;
          private PhotoCamera _photoCamera;

          public QRPage()
         {  
             InitializeComponent();
 
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(1000);
            _timer.Tick += (o, arg) => ScanPreviewBuffer();
        }
        //初始化摄像头
         protected override void OnNavigatedTo(System. Windows. Navigation. NavigationEventArgs  e)
        {
            _photoCamera = new PhotoCamera();
       
            _photoCamera.Initialized += OnPhotoCameraInitialized;
            
            _previewVideo.SetSource(_photoCamera);
 
            CameraButtons.ShutterKeyHalfPressed += (o, arg) => _photoCamera.Focus();
 
            base.OnNavigatedTo(e);
        }

        //初始化二维码识别器
         private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            
            int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
            _luminance = new PhotoCameraLuminanceSource(width, height);
           
            _reader = new QRCodeReader();
 
            Dispatcher.BeginInvoke(() => {
            _previewTransform.Rotation = _photoCamera.Orientation;
            _timer.Start();
            });
        }

        //扫描图像缓存
         private void ScanPreviewBuffer()
         {

             try
                {
                 _photoCamera.Focus();
                 _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);

                var binBitmap = new BinaryBitmap(binarizer);
                var result = _reader.decode(binBitmap);
                if (result != null)
                {

                    Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
                }
                }
            catch
                {
                    }
        }
         //解析二维码文字信息
          private void DisplayResult(string text)
         {
              // str = {"require_login":true,"title":"开源中国 OSC 源创会第 24 期（济南）","type":1,"url":"http://www.oschina.net/action/qrcode/signin?id=153149"}
               QRInfo _QRInfo = JsonConvert.DeserializeObject<QRInfo>(text);
               string url = _QRInfo.url;
               doHttpGet(url);
            }
               
        //进行签到请求
          private void doHttpGet(string url)
          {
              HttpWebRequest httpwebRequest = HttpWebRequest.CreateHttp(url);
              httpwebRequest.Headers["User-Agent"] = Config.UserAgent;
              httpwebRequest.Headers["Cookie"] = Config.Cookie;
              httpwebRequest.BeginGetResponse((result) =>
              {
                  HttpWebRequest httprequest = (HttpWebRequest)result.AsyncState;
                  HttpWebResponse httpresponse = httprequest.EndGetResponse(result) as HttpWebResponse;
                  Stream webstream = httpresponse.GetResponseStream();
                  StreamReader streamreader = new StreamReader(webstream);
                  string str = streamreader.ReadToEnd();

                  this.Dispatcher.BeginInvoke(() =>
                  {
                      string text = "";
                      if (str.StartsWith("{\"error\":"))
                      {

                          QRInfo_Error error = JsonConvert.DeserializeObject<QRInfo_Error>(str);
                          text = error.error;
                      }
                      else
                      {
                          QRInfo_Msg msg = JsonConvert.DeserializeObject<QRInfo_Msg>(str);
                          text = msg.msg;
                      }
                      MessageBox.Show(text);
                      Tool.To("/MainPage.xaml");

                  });
                  //异步调用完成
              }, httpwebRequest);

          }
    }
}